package com.citycloud.ccuap.tc.oauth2.config.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.citycloud.ccuap.tc.common.result.ResultCodeEnum;
import com.citycloud.ccuap.tc.common.result.ResultObject;
import com.citycloud.ccuap.tc.oauth2.config.CustomerProperties;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class CustomerAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        Map<String, String> data = new HashMap<>(4);
        data.put("loginPage", CustomerProperties.authenticationFrontendUrl);
        data.put("loginUrl", CustomerProperties.authenticationBackendUrl + "/login");
        ResultObject result = ResultObject.getInstance().error(ResultCodeEnum.TOKEN_UNAUTHORIZED, "请先登陆");
        result.setData(data);

        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().print(mapper.writeValueAsString(result));
    }
}
